# -*- coding: utf-8 -*-
import os

from log.logger import logger
from misc.exec_cmd import (
    exec_cmd,
)


def read_file(file_name, mode='r'):
    try:
        with open(file_name, mode) as f:
            content = f.read()
    except Exception, e:
        logger.error("read file [{0}] failed, [{1}]".format(file_name, e))
        return None
    return content


def write_file(file_name, content):
    try:
        with open(file_name, "w") as f:
            f.write("{0}".format(content))
    except Exception, e:
        logger.error("write file [{0}] failed, [{1}]".format(file_name, e))
        return False
    return True


def append_file(file_name, content):
    try:
        with open(file_name, "a") as f:
            f.write("{0}".format(content))
    except Exception, e:
        logger.error("append file [{0}] failed, [{1}]".format(file_name, e))
        return False
    return True


def remove_path(path):
    if os.path.exists(path):
        result = exec_cmd('rm -rf {0}'.format(path))
        if result['ret'] != 0:
            logger.error("remove path [{0}] failed, [{1}]!".format(path, result))
            return False
        return True
    else:
        logger.info("the path [{0}] to be removed is not exists!".format(path))
        return True
